# -*- coding: UTF-8 -*-
"""
@描述：数据库连接池管理模块
@作者：LSY
@版本：V1.0
@创建时间：2017-05-17 上午8:43:14
"""

import pymysql
import time
from DBUtils.PooledDB import PooledDB
import taoguba_comment_spider.DB_config as Config

'''
@功能：PT数据库连接池
'''
class PTConnectionPool(object):
    __pool = None

    def __enter__(self):
        self.conn = self.getConn()
        self.cursor = self.conn.cursor()
        return self

    def getConn(self):
        if self.__pool is None:
            self.__pool = PooledDB(creator=pymysql, mincached=Config.DB_MIN_CACHED , maxcached=Config.DB_MAX_CACHED,
                                   maxshared=Config.DB_MAX_SHARED, maxconnections=Config.DB_MAX_CONNECYIONS,
                                   blocking=Config.DB_BLOCKING, maxusage=Config.DB_MAX_USAGE,
                                   setsession=Config.DB_SET_SESSION,
                                   host=Config.DB_TEST_HOST, port=Config.DB_TEST_PORT,
                                   user=Config.DB_TEST_USER, passwd=Config.DB_TEST_PASSWORD,
                                   db=Config.DB_TEST_DBNAME, use_unicode=True, charset=Config.DB_CHARSET)
        return self.__pool.connection()

    """
    @summary: 释放连接池资源
    """
    def __exit__(self, type, value, trace):
        self.cursor.close()
        self.conn.close()

'''
@功能：获取PT数据库连接
'''
def getPTConnection():
    return PTConnectionPool()

class PTConnectionHelper(object):

    @staticmethod
    def executeSql(sql, sec=5):
        while True:
            try:
                with getPTConnection() as db:
                    db.cursor.execute(sql)
                    results = db.cursor.fetchall()
                    return results
            except:
                time.sleep(sec)
                continue

    @staticmethod
    def commitSql(sql, sec=5):
        while True:
            try:
                with getPTConnection() as db:
                    ib = db.cursor.execute(sql)
                    return ib
            except:
                time.sleep(sec)
                continue
